package com.affinity.impl;

import java.util.Arrays;

import com.affinity.*;

/**
 * @author cheremin
 * @since 27.04.12,  18:51
 */
public class SimpleCPULayoutService implements CPULayoutService {

    protected final CPU[] processors;

    public SimpleCPULayoutService() {
        this( Runtime.getRuntime().availableProcessors() );
    }

    public SimpleCPULayoutService( final int processorsCount ) {
        processors = new CPU[processorsCount];
        for ( int i = 0; i < processors.length; i++ ) {
            processors[i] = new CPUImpl( i );
        }
    }

    @Override
    public Iterable<? extends CPU> availableCPUs() {
        return Arrays.asList( processors );
    }

	@Override
	public int cpusCount() {
		return processors.length;
	}

	@Override
    public CPU cpu( final int cpuNo ) {
        if ( cpuNo < 0 ) {
            throw new IllegalArgumentException( "cpuNo=" + cpuNo + " must not be negative" );
        }
        if ( cpuNo > processors.length ) {
            throw new IllegalArgumentException( "cpuNo=" + cpuNo + " must not be >= " + processors.length );
        }
        return processors[cpuNo];
    }

    @Override
    public boolean isTopologyServiceSupported() {
        return false;
    }

    @Override
    public CPUTopologyService asTopologyService() throws UnsupportedOperationException {
        throw new UnsupportedOperationException( "Not implemented" );
    }

    protected static class CPUImpl implements CPU {
        private final int id;

        public CPUImpl( final int id ) {
            this.id = id;
        }

        @Override
        public int id() {
            return id;
        }

        @Override
        public int hashCode() {
            return id;
        }

        @Override
        public boolean equals( final Object o ) {
            if ( this == o ) {
                return true;
            }
            if ( o == null || getClass() != o.getClass() ) {
                return false;
            }

            final CPUImpl cpu = ( CPUImpl ) o;

            if ( id != cpu.id ) {
                return false;
            }

            return true;
        }

        @Override
        public String toString() {
            return String.format( "CPUInfo[%d]", id() );
        }
    }
}
